package com.example.psychologicalappointmentsystem.Controller;

import com.example.psychologicalappointmentsystem.Entity.Question;
import com.example.psychologicalappointmentsystem.Entity.UserQuestionnaire;
import com.example.psychologicalappointmentsystem.Entity.UserQuestionnaireSummary;
import com.example.psychologicalappointmentsystem.Enum.AnxietyLevel;
import com.example.psychologicalappointmentsystem.JpaRepository.QuestionRepository;
import com.example.psychologicalappointmentsystem.JpaRepository.UserQuestionnaireRepository;
import com.example.psychologicalappointmentsystem.JpaRepository.UserQuestionnaireSummaryRepository;
import com.example.psychologicalappointmentsystem.Object.UserQuestionnaireAll;
import com.example.psychologicalappointmentsystem.service.QuestionnaireService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/questionnaire")
public class QuestionnaireController {
    @Autowired
    private UserQuestionnaireRepository userQuestionnaireRepository;

    @Autowired
    private UserQuestionnaireSummaryRepository userQuestionnaireSummaryRepository;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionnaireService questionnaire;

    //情感分析模块部署路径
    public static String SENTIMENT_ANALYSIS_URL = "http://49.234.205.23:5000/analyze_sentiment";

    @PostMapping("/submit")
    public ResponseEntity<?> submitQuestionnaire(@RequestBody List<UserQuestionnaire> userQuestionnaires) {
        try {
            List<Question> questions = questionRepository.findAll();
            int i = 0;
            for (Question question:questions){
                userQuestionnaires.get(i).setQuestionId(question.getId());
                i++;
            }
            if (userQuestionnaireRepository.findByUserId(userQuestionnaires.get(1).getUserId()).size()==0){
                // 保存问卷回答
                userQuestionnaireRepository.saveAll(userQuestionnaires);
            }

            // 对每个问题的答案进行情感分析
//            List<Map<String, Object>> sentimentResults = new ArrayList<>();
//            StringBuilder summary = new StringBuilder(); // 用于存放总结
//            int positiveCount = 0; // 记录积极情感问题数量
            int negativeCount = 0; // 记录消极情感问题数量
            Long userId = 0L;
            for (UserQuestionnaire userQuestionnaire : userQuestionnaires) {
                String answer = userQuestionnaire.getAnswer();
                String questionText = userQuestionnaire.getQuestionText();
                StringBuilder analyzeText = new StringBuilder(questionText);
                String sentiment;
                if (answer.equals("是")){
                    // 调用情感分析模型进行分析
                    sentiment = questionnaire.analyzeSentiment(questionText);
                }else{
                    String analyzeTextNo = analyzeText.insert(1,"没有").toString();
                    sentiment = questionnaire.analyzeSentiment(analyzeTextNo);
                }
                userId = userQuestionnaire.getUserId();

                // 根据情感分析结果更新总结
//                if ("positive".equals(sentiment)) {
//                    positiveCount++;
//                } else
                if ("NEGATIVE".equals(sentiment)) {
                    negativeCount++;
                }
            }
            UserQuestionnaireSummary userQuestionnaireSummary = new UserQuestionnaireSummary();
            userQuestionnaireSummary.setUserId(userId);
            
            if (negativeCount<=5){
                userQuestionnaireSummary.setSummary("您的整体情绪状态较为积极。无明显焦虑情绪，多出去走走看看自然风景吧~");
                userQuestionnaireSummary.setAnxietyLeverl(String.valueOf(AnxietyLevel.NO_ANXIETY));
            }else if (negativeCount<=10 && negativeCount>5){
                userQuestionnaireSummary.setSummary("您目前有轻微的焦虑情绪，但是人生不如意之事十有八九，要让自已快乐，就必须给自己减压，减压的方法就是学会忘记，人生需要能拿得起，多一点快乐，少一点烦恼，祝福永相伴！");
                userQuestionnaireSummary.setAnxietyLeverl(String.valueOf(AnxietyLevel.MILD_ANXIETY));
            }else if(negativeCount<=15&&negativeCount>10){
                userQuestionnaireSummary.setSummary("您目前有中度的焦虑情绪，可能需要心理咨询师陪你聊聊天喔！");
                userQuestionnaireSummary.setAnxietyLeverl(String.valueOf(AnxietyLevel.MODERATE_ANXIETY));
            }else if(negativeCount>15){
                userQuestionnaireSummary.setSummary("您目前有重度的焦虑情绪，需要心理咨询师陪你聊聊天喔！很多现代人身上都肩负着很大的责任，随之而来的压力也有很多，不过我们一定要让这些不安的情绪及时的释放出去，才能更好的舒缓自己的心情。");
                userQuestionnaireSummary.setAnxietyLeverl(String.valueOf(AnxietyLevel.SEVERE_ANXIETY));
            }
                userQuestionnaireSummary.setIsCompleted(1);
                userQuestionnaireSummaryRepository.update(userQuestionnaireSummary);
            return ResponseEntity.ok(userQuestionnaireSummary.getSummary());//返回情绪总结
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("问卷提交失败");
        }
    }

    // 获取所有问题
    @GetMapping("/questions")
    public ResponseEntity<List<Question>> getAllQuestions() {
        List<Question> questions = questionRepository.findAll();
        return ResponseEntity.ok(questions);
    }

    // 获取问卷填写的信息
    @GetMapping("/viewQuestionnaire")
    public ResponseEntity<?> viewQuestionnaire(Long userId) {
        UserQuestionnaireAll viewQuestionnaire = new UserQuestionnaireAll();
        //查询用户分析总结
        UserQuestionnaireSummary userQuestionnaireSummary = userQuestionnaireSummaryRepository.find1UserId(userId);
        viewQuestionnaire.setUserId(userId);
        viewQuestionnaire.setSummary(userQuestionnaireSummary.getSummary());
        //查用户的问题与答案
        List<UserQuestionnaire> questionsAndAnswers = userQuestionnaireRepository.findByUserId(userId);
        Map<String,String> userQA = new HashMap<>();
        //遍历问题与答案进行汇总
        for(UserQuestionnaire q:questionsAndAnswers){
            userQA.put(q.getQuestionText(),q.getAnswer());
        }
//        System.out.println(userQA.entrySet());
        viewQuestionnaire.setQuestionAndAnswer(new ArrayList<>(userQA.entrySet()));
        return ResponseEntity.ok(viewQuestionnaire);
    }

}
